import { createRouter, createWebHashHistory } from 'vue-router'
import { contan } from './router'
import store from '@/store'
import useUserStore from '@/store/modules/user'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css' // 导入进度条样式
NProgress.configure({ showSpinner: false })
const userStore = useUserStore(store)

const router = createRouter({
  history: createWebHashHistory(),
  routes: contan,
  scrollBehavior() {
    // 始终滚动到顶部
    return { top: 0 }
  },
})

//路由鉴权
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = '小乌龟-' + to.meta.title
  const token = userStore.token
  const username = userStore.username
  if (token) {
    //已登录
    //不能去login
    if (to.path == '/login') {
      next({ path: '/' })
    } else {
      if (username) {
        next()
      } else {
        //需要给用户信息
        try {
          await userStore.getUserInfo()
          //有用户信息
          next({ ...to })
        } catch (err) {
          //token已过期
          await userStore.exitLogin()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    //未登录
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login' })
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})

export default router
